package com.database.controller;

import com.rent.common.exception.Asserts;
import com.rent.common.pojo.ResultJSON;
import org.springframework.web.bind.annotation.RequestBody;

import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Date;

/**
 * @Author zhang
 * @create 2022/4/2 17:39
 */
public interface UpdateController<T, PK extends Serializable> extends BaseController<T, PK> {


    default ResultJSON<String> update(@RequestBody T model) {
        try {
            Class<?> clazz = model.getClass();
            Field[] fields = clazz.getDeclaredFields();
            if (fields.length == 0) return saveFail();
            for (Field field : fields) {
                String name = field.getName();
                if ("serialVersionUID".equals(name)) {
                    continue;
                }
                // 设置字段可访问（必须，否则报错）
                field.setAccessible(true);
                PropertyDescriptor pd = new PropertyDescriptor(name, clazz);
                if ("updateDate".equalsIgnoreCase(name) || "updateTime".equalsIgnoreCase(name)) {
                    pd.getWriteMethod().invoke(model, new Date());
                }
                if ("updateUserId".equalsIgnoreCase(name)) {
                    if (Integer.class.equals(pd.getPropertyType())) {
                        pd.getWriteMethod().invoke(model, getAccountId());
                    } else if (String.class.equals(pd.getPropertyType())) {
                        pd.getWriteMethod().invoke(model, String.valueOf(getAccountId()));
                    }
                    continue;
                }
                if ("updateUser".equalsIgnoreCase(name)) {
                    pd.getWriteMethod().invoke(model, getUsername());
                }
            }
        } catch (Exception e) {
            Asserts.fail(e.getMessage());
        }
        int i = getSuperService().updateByPrimaryKeySelective(model);
        if (0 == i) return saveFail();
        return saveSuccess();
    }

}
